#ifndef QMLBRIDGE_H
#define QMLBRIDGE_H

#include <QObject>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QVariant>
#include <QDateTime>
#include "devicecontroller.h"
#include "samplingmanager.h"
#include "auditlogger.h"
#include "usersession.h"
#include "permissionmanager.h"

class QmlBridge : public QObject
{
    Q_OBJECT
    Q_PROPERTY(bool isUserLoggedIn READ isUserLoggedIn NOTIFY userLoginStatusChanged)
    Q_PROPERTY(QString currentUser READ getCurrentUser NOTIFY currentUserChanged)
    Q_PROPERTY(QString currentUserRole READ getCurrentUserRole NOTIFY currentUserRoleChanged)
    Q_PROPERTY(bool hasDeviceControl READ hasDeviceControl NOTIFY permissionsChanged)
    Q_PROPERTY(bool hasUserManagement READ hasUserManagement NOTIFY permissionsChanged)
    Q_PROPERTY(bool hasDataExport READ hasDataExport NOTIFY permissionsChanged)

public:
    explicit QmlBridge(QObject *parent = nullptr);
    ~QmlBridge();

    // 初始化方法
    bool initialize(QQmlApplicationEngine* engine);
    void registerQmlTypes();
    void setupContextProperties();

    // 用户认证相关
    Q_INVOKABLE bool loginUser(const QString& username, const QString& password);
    Q_INVOKABLE void logoutUser();
    Q_INVOKABLE bool logUserLogin(const QString& username, bool success);
    Q_INVOKABLE bool logUserLogout(const QString& username);
    Q_INVOKABLE bool isUserLoggedIn() const;
    Q_INVOKABLE QString getCurrentUser() const;
    Q_INVOKABLE QString getCurrentUserRole() const;
    
    // 权限检查
    Q_INVOKABLE bool hasDeviceControl() const;
    Q_INVOKABLE bool hasUserManagement() const;
    Q_INVOKABLE bool hasDataExport() const;
    Q_INVOKABLE bool hasPermission(const QString& permission) const;
    
    // 设备控制接口
    Q_INVOKABLE bool startDevice();
    Q_INVOKABLE bool stopDevice();
    Q_INVOKABLE bool startSampling(int mode, int parameter);
    Q_INVOKABLE bool stopSampling();
    Q_INVOKABLE QVariant getDeviceStatus() const;
    Q_INVOKABLE QVariant getDeviceParameters() const;
    
    // 采样管理接口
    Q_INVOKABLE int createSamplingTask(const QString& taskName, int mode, int parameter, 
                                      const QString& scheduledTime, bool isRecurring);
    Q_INVOKABLE bool deleteSamplingTask(int taskId);
    Q_INVOKABLE QVariantList getSamplingTasks() const;
    Q_INVOKABLE QVariantList getSamplingHistory() const;
    
    // 用户管理接口
    Q_INVOKABLE bool createUser(const QString& username, const QString& password, 
                               const QString& role, const QString& fullName);
    Q_INVOKABLE bool deleteUser(const QString& username);
    Q_INVOKABLE bool changeUserPassword(const QString& username, const QString& newPassword);
    Q_INVOKABLE QVariantList getAllUsers() const;
    
    // 审计日志接口
    Q_INVOKABLE QVariantList getAuditLogs(const QString& fromDate, const QString& toDate, 
                                         const QString& userId, const QString& action) const;
    Q_INVOKABLE bool exportAuditLogs(const QString& filePath, const QString& format) const;
    
    // 数据可视化接口
    Q_INVOKABLE QVariantList getFlowRateHistory(int hours) const;
    Q_INVOKABLE QVariantList getBatteryHistory(int hours) const;
    Q_INVOKABLE QVariantList getSamplingStatistics(int days) const;
    Q_INVOKABLE QVariant getDashboardData() const;
    
    // 系统设置接口
    Q_INVOKABLE bool saveSystemSettings(const QVariantMap& settings);
    Q_INVOKABLE QVariantMap getSystemSettings() const;
    Q_INVOKABLE bool performSystemBackup(const QString& backupPath);
    Q_INVOKABLE bool restoreSystemBackup(const QString& backupPath);
    
    // 消息通知接口
    Q_INVOKABLE void showNotification(const QString& title, const QString& message, int type);
    Q_INVOKABLE void showConfirmDialog(const QString& title, const QString& message, 
                                      const QString& callback);

    // 设置组件引用
    void setDeviceController(DeviceController* controller);
    void setSamplingManager(SamplingManager* manager);
    void setAuditLogger(AuditLogger* logger);
    void setUserSession(UserSession* session);
    void setPermissionManager(PermissionManager* manager);

signals:
    void userLoginStatusChanged(bool isLoggedIn);
    void currentUserChanged(const QString& username);
    void currentUserRoleChanged(const QString& role);
    void permissionsChanged();
    void deviceStatusChanged(const QVariant& status);
    void samplingTaskCreated(int taskId, const QString& taskName);
    void samplingTaskCompleted(int taskId, bool success);
    void notificationRequested(const QString& title, const QString& message, int type);
    void confirmDialogRequested(const QString& title, const QString& message, const QString& callback);
    void systemError(const QString& error);

private slots:
    void onUserLogin(const QString& userId);
    void onUserLogout();
    void onDeviceStatusChanged(DeviceStatus status);
    void onSamplingCompleted(const SamplingRecord& record);
    void onDeviceError(const QString& error);

private:
    // 私有成员变量
    QQmlApplicationEngine* m_engine;
    DeviceController* m_deviceController;
    SamplingManager* m_samplingManager;
    AuditLogger* m_auditLogger;
    UserSession* m_userSession;
    PermissionManager* m_permissionManager;
    
    // 私有方法
    void logUserOperation(const QString& operation, const QString& details);
    QVariantMap deviceParametersToVariant(const DeviceParameters& params) const;
    QVariantMap samplingRecordToVariant(const SamplingRecord& record) const;
    QVariantMap samplingTaskToVariant(const SamplingTask& task) const;
    bool validateUserInput(const QString& input, const QString& type) const;
    void updateUserPermissions();
    
    // 数据转换辅助方法
    SamplingMode intToSamplingMode(int mode) const;
    QString samplingModeToString(SamplingMode mode) const;
    QString deviceStatusToString(DeviceStatus status) const;
    QDateTime stringToDateTime(const QString& dateTimeStr) const;
    QString dateTimeToString(const QDateTime& dateTime) const;
};

// QML中使用的枚举类型
class QmlEnums : public QObject
{
    Q_OBJECT
public:
    enum SamplingMode {
        TimedSampling = 0,
        VolumeSampling = 1
    };
    Q_ENUM(SamplingMode)
    
    enum DeviceStatus {
        DeviceIdle = 0,
        DeviceSampling = 1,
        DeviceStopping = 2,
        DeviceError = 3,
        DeviceMaintenance = 4
    };
    Q_ENUM(DeviceStatus)
    
    enum NotificationType {
        InfoNotification = 0,
        WarningNotification = 1,
        ErrorNotification = 2,
        SuccessNotification = 3
    };
    Q_ENUM(NotificationType)
    
    enum UserRole {
        ViewerRole = 1,
        OperatorRole = 2,
        AdminRole = 3
    };
    Q_ENUM(UserRole)
};

#endif // QMLBRIDGE_H